package com.formssi.service;

import com.formssi.mapper.UserMapper;
import com.formssi.pojo.User2;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: ajims
 * @time: 2021/6/28 15:13
 */
@Service
public class ScheduledService {

    @Autowired
    @Qualifier("userServiceImpl")
    UserService userService;

    //每天中午12点调度任务执行
//    @Scheduled(cron = "0 0 12 * * ?")
    @Scheduled(cron = "0/30 * * * * ?")
    public void setAge() throws Exception {
        List<User2> users = new ArrayList<User2>();
        users = userService.findAllUser();
        int age;
        for (User2 user2 : users) {
            if(user2.getAge()!=(age = getAge(user2.getBirthday()))){
                user2.setAge(age);
                user2.setModiTime(new Date());
                userService.update(user2);
            }
        }
    }

    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    public static  Date parse(String strDate) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }
}
